# code:utf8

import json
import math
import logging
from datetime import datetime
from pyquery import PyQuery
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.model.items import Catalog, Brand, Supplier, Sku, ItemData, BidItem, Bid, Spu, ItemDataSupply, SpuSupply
from zc_core.util.common import parse_number, parse_time
from zc_core.util.sku_id_parser import convert_id2code
from zc_core.util.encrypt_util import md5
from zc_core.util.encrypt_util import double_base64_encode, md5
from plap_zc.matcher import *
from plap_zc.items import PlapZcSku, PlapZcFull

logger = logging.getLogger('rule')


# 解析catalog列表
def parse_catalog(response):
    jpy = PyQuery(response.text)
    div_list = jpy('div.catalog_type_s div.item div.product-wrap div.cfminlist')

    cats = list()
    for div in div_list.items():
        # 一级分类
        cat1_name = div('div.cfname').text().strip().strip('：')
        cat1_id = md5(cat1_name)
        cat1 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat1)
        # 二级分类
        cat2_links = div.next().eq(0)('a')
        for cat2_link in cat2_links.items():
            cat2_id = match_cat_id(cat2_link.attr('href'))
            cat2_name = cat2_link.text().strip()
            cat2 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat2)

    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 2:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


def parse_supplier_page(response, size):
    json_data = json.loads(response.text)
    return math.ceil(int(json_data.get('userarea', {}).get('count', 1)) / size)


# 解析brand列表
def parse_supplier(response):
    meta = response.meta
    json_data = json.loads(response.text)
    suppliers = []
    for data in json_data.get('userarea', {}).get('searchGysList', []):
        supplier = Supplier()
        supplier['id'] = data.get('gysGuid')
        supplier['name'] = data.get('gysName')
        supplier['batchNo'] = meta.get('batchNo')
        supplier['mobile'] = data.get('localMobile')
        supplier['sales'] = data.get('sales')
        supplier['score'] = data.get('score')
        suppliers.append(supplier)
    return suppliers


# 解析sku列表页数
def parse_sku_page(response):
    jpy = PyQuery(response.text)
    last_link = jpy('div.pagination li.last a').attr('href')
    return match_sku_total_page(last_link)


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    json_data = json.loads(response.text)
    skus = list()
    for data in json_data.get('userarea', {}).get('productList', []):
        sku = PlapZcSku()
        sku_name = data.get('productname')
        sku['skuName'] = sku_name
        sku_id = data.get('productguid')
        sku['skuId'] = sku_id
        catalog_name = data.get('cname')
        sku['catalogName'] = catalog_name
        origin_price = data.get('indicativeprice')
        sku['originPrice'] = origin_price
        catalog_id = data.get('cid')
        sku['catalogId'] = catalog_id
        goods_type = data.get('tuijianname')
        sku['goodsType'] = goods_type
        brand_name = data.get('brandname')
        sku['brandName'] = brand_name
        status_name = data.get('statusname')
        sku['statusName'] = status_name
        sku['batchNo'] = batch_no
        sku['skuCode'] = data.get('xdproductcode')
        sku['materialCode'] = data.get('productcode')
        skus.append(sku)
    return skus


# 处理军网上线商品
def parse_on_line_sku(response):
    meta = response.meta
    supplier_id = meta.get('supplierId')
    supplier_name = meta.get('supplierName')
    batch_no = meta.get('batchNo')
    if response.text:
        json_data = json.loads(response.text)
        data_list = json_data.get("userarea", {}).get('productslist', {}).get('Goods', [])
        skus = []
        for data in data_list:
            sku = PlapZcFull()
            sku['skuName'] = data.get('productname')
            product_id = data.get('productid')
            sku['supplierId'] = supplier_id
            sku['batchNo'] = batch_no
            sku['productId'] = product_id
            sku['skuId'] = str(product_id) + ":" + str(supplier_id)
            sku['supplierName'] = supplier_name
            sku['originPrice'] = data.get('price')
            sku['floorPrice'] = data.get('lowprice')
            sku['brandName'] = data.get('brandname')
            sku['catalogId'] = data.get('cid')
            sku['soldAmount'] = data.get('salesvolume')
            sku['mainImgs'] = [i.get('bimg') for i in data.get('pic')]
            skus.append(sku)
        return skus
    return []


def parse_on_line_page(response, size):
    json_data = json.loads(response.text)
    return math.ceil(int(json_data.get('userarea', {}).get('productslist', {}).get('AllCountNum', 1)) / size)


def parse_skuxx(response, item):
    if response.text:
        json_data = json.loads(response.text).get('userarea', {}).get('baojiainfo', {})
        item['salePrice'] = json_data.get('price')
        item['stock'] = json_data.get('stock')
    return item


def parse_totals(response, size):
    json_data = json.loads(response.text)
    totals = math.ceil(int(json_data.get('userarea', {}).get('count', 1)) / size)
    return totals


# ==============================================
# 解析sku列表页数
def parse_spu_page(response):
    jpy = PyQuery(response.text)
    last_link = jpy('div.pagination li.last a').attr('href')
    return match_spu_total_page(last_link)


# 解析sku列表
def parse_spu(response):
    spus = list()
    meta = response.meta
    batch_no = meta.get('batchNo')
    cat_helper = CatalogHelper()
    jpy = PyQuery(response.text)
    trs = jpy('table.Ptable tr')
    if trs and trs.size() > 1:
        for tr in trs.items():
            tds = tr('td')
            if tds:
                spu = Spu()
                cat_str = tds.eq(1).attr('title').strip()
                link = tds.eq(2)('a').attr('href')
                sku_name = tds.eq(2)('a').attr('title').strip()
                brand = tds.eq(3).text().strip()
                origin_price_str = tds.eq(4)('span.hide').text().strip()
                origin_price = match_origin_price(origin_price_str)
                # 删除干扰元素
                tds.eq(4)('span').remove()
                limit_price = tds.eq(4).text().strip().strip('¥')
                spu_id = match_commodity_id(link)
                spu['spuId'] = spu_id
                spu['skuName'] = sku_name
                spu['originPrice'] = parse_number(origin_price)
                spu['limitPrice'] = parse_number(limit_price)
                if brand:
                    spu['brandId'] = md5(brand)
                    spu['brandName'] = brand
                if cat_str:
                    cat_name_arr = cat_str.split('-')
                    spu['catalog1Name'] = cat_name_arr[0]
                    spu['catalog2Name'] = cat_name_arr[1]
                cat_helper.fill(spu)
                spu['batchNo'] = batch_no
                spus.append(spu)

    return spus


def build_spu_log(cat_id, page, count, batch_no):
    log = SpuPageLog()
    log['catId'] = cat_id
    log['page'] = page
    log['count'] = count
    log['batchNo'] = batch_no

    return log


# ===============================================


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    spu_id = meta.get('spuId')
    material_code = meta.get('materialCode')
    spu = meta.get('spu')

    data_list = list()
    jpy = PyQuery(response.text)
    lis = jpy('ul li')
    if lis:
        for li in lis.items():
            row = li('input')
            sku_id = row.attr('value')
            sale_price = parse_number(row.attr('price'))
            if sku_id and sale_price > 0:
                sp_name = row.attr('title')
                sp_sku_id = row.attr('sku').strip('(').strip(')')
                sp_sku_link = row.attr('url').strip()
                item = ItemData()
                item['batchNo'] = batch_no
                item['skuId'] = sku_id
                item['spuId'] = spu_id
                item['materialCode'] = material_code
                item['salePrice'] = sale_price
                item['skuName'] = spu.get('skuName')
                item['catalog1Id'] = spu.get('catalog1Id', '')
                item['catalog1Name'] = spu.get('catalog1Name', '')
                item['catalog2Id'] = spu.get('catalog2Id', '')
                item['catalog2Name'] = spu.get('catalog2Name', '')
                item['brandId'] = spu.get('brandId', '')
                item['brandName'] = spu.get('brandName', '')
                item['originPrice'] = spu.get('originPrice', sale_price)
                if sp_name:
                    item['supplierId'] = md5(sp_name)
                    item['supplierName'] = sp_name
                if sp_sku_id:
                    item['supplierSkuId'] = sp_sku_id
                    sp_sku_code = sp_sku_id
                    # 得力
                    if '得力' in sp_name:
                        sp_sku_code = convert_id2code('deli', sp_sku_id)
                    item['supplierSkuCode'] = sp_sku_code
                if sp_sku_link and (sp_sku_link.startswith('http://') or sp_sku_link.startswith(
                        'https://')) and sp_sku_link != '#none':
                    item['supplierSkuLink'] = sp_sku_link
                item['genTime'] = datetime.utcnow()
                data_list.append(item)

    return data_list


# 解析销量
def parse_sales(response):
    meta = response.meta
    sku_id = meta.get('skuId')
    batch_no = meta.get('batchNo')
    jpy = PyQuery(response.text)
    amt = jpy('div.cumulativeamount')
    if amt and amt.text():
        sold_amt = parse_number(amt.text().strip())
        item = ItemDataSupply()
        item['batchNo'] = batch_no
        item['skuId'] = sku_id
        item['soldAmount'] = sold_amt

        return item


# 解析商品编号
def parse_commodity(response):
    meta = response.meta
    spu_id = meta.get('spuId')
    batch_no = meta.get('batchNo')
    jpy = PyQuery(response.text)
    code_div = jpy('div.goods_price div.attribute > div.dt:contains("商品编号：") + div.gs')
    if code_div:
        code_div('span#psku_tag').remove()
        material_code = code_div.text().strip()
        if material_code:
            item = SpuSupply()
            item['batchNo'] = batch_no
            item['spuId'] = spu_id
            item['materialCode'] = material_code

            return item


# 解析商品编号
def parse_material_code(response):
    jpy = PyQuery(response.text)
    code_div = jpy('div.goods_price div.attribute > div.dt:contains("商品编号：") + div.gs')
    if code_div:
        code_div('span#psku_tag').remove()
        return code_div.text().strip()


# =========================
# 解析ItemData
def parse_bid(response):
    meta = response.meta
    link_id = meta.get('linkId')
    status = meta.get('status')
    jpy = PyQuery(response.text)

    bid = Bid()
    project_id = jpy('td.zh_color:contains("项目编号：") ~ td').text().strip()
    project_name = jpy('td.zh_color:contains("项目名称：") ~ td').text().strip()
    zb_price = jpy('td.zh_color:contains("中标价：") ~ td').text().replace('元', '').strip()
    if not zb_price:
        zb_price = match_bid_price(response.text)
    total_price = parse_number(zb_price)
    supplier = jpy('td.zh_color:contains("祝贺供应商：") ~ td font.textm').text().strip()
    if not supplier:
        supplier = jpy('table#table thead tr span.lh28').eq(0)('font.textm').text().strip()
    mobile = jpy('td.zh_color:contains("联系人电话：") ~ td').text().strip()
    address = jpy('td.zh_color:contains("收货地点：") ~ td').text().strip()
    start_time = jpy('td.zh_color:contains("网上竞价开始时间：") ~ td').text().strip()
    if not start_time:
        return None
    start_time = parse_time(start_time, fmt='%Y-%m-%d %H:%M:%S')
    batch_no = time_to_batch_no(start_time)
    bid['projectId'] = project_id
    bid['linkId'] = link_id
    bid['projectName'] = project_name
    bid['startTime'] = start_time
    bid['mobile'] = mobile
    bid['address'] = address
    if address and ' ' in address:
        arr = address.split(' ')
        if arr and len(arr) > 3:
            bid['province'] = arr[0].strip()
            bid['city'] = arr[1].strip()
            bid['district'] = arr[2].strip()
    bid['mobile'] = mobile
    bid['supplierName'] = supplier
    bid['totalPrice'] = total_price
    bid['status'] = int(status)
    bid['genTime'] = datetime.utcnow()
    bid['batchNo'] = batch_no

    items = list()
    trs = jpy('table.Ptable tr')
    if trs and trs.size() > 1:
        for idx in range(1, trs.size()):
            tr = trs.eq(idx)
            tds = tr('td')
            link_js = tds('a.a_button').attr('onclick')
            item_id = match_bid_item_id(link_js)
            if not item_id:
                logger.error('详情编号异常：%s' % link_id)
                continue
            item = BidItem()
            item['itemId'] = item_id
            item['projectId'] = project_id
            item['itemName'] = tds.eq(0).text().strip()
            item['itemBrand'] = tds.eq(1).text().strip()
            item['itemModel'] = tds.eq(2).text().strip()
            item['itemUnit'] = tds.eq(3).text().strip()
            item['itemAmount'] = tds.eq(4).text().strip()
            item['itemPrice'] = tds.eq(5).text().strip()
            item['startTime'] = start_time
            item['batchNo'] = batch_no
            items.append(item)

    return (bid, items)


# 解析BidItemDetail
def parse_bid_item_detail(response, cat_helper):
    meta = response.meta
    item = meta.get('item')
    jpy = PyQuery(response.text)
    cat_td = jpy('table td.zh_color:contains("商品分类：") + td')
    desc_td = jpy('table td.zh_color:contains("产品描述：") + td')
    item['note'] = desc_td.text().strip()
    if cat_td:
        cat2_name = cat_td.text().strip()
        item['catalog2Name'] = cat2_name
        cat_helper.fill(item)
        if not item.get('catalog1Name') or not item.get('catalog1Id'):
            cat1_name = '未知'
            item['catalog1Id'] = '00000'
            item['catalog1Name'] = cat1_name
        if not item.get('catalog2Id') and cat2_name:
            item['catalog2Id'] = md5(cat2_name)

    return item


# 解析BidItemDetail
def parse_bid_item_detail_single(response, cat_helper):
    meta = response.meta
    item_id = meta.get('itemId')
    batch_no = meta.get('batchNo')
    jpy = PyQuery(response.text)
    cat_td = jpy('table td.zh_color:contains("商品分类：") + td')
    desc_td = jpy('table td.zh_color:contains("产品描述：") + td')
    if cat_td:
        item = BidItem()
        item['itemId'] = item_id
        item['batchNo'] = int(batch_no)
        item['note'] = desc_td.text().strip()
        cat2_name = cat_td.text().strip()
        item['catalog2Name'] = cat2_name
        cat_helper.fill(item)
        if not item.get('catalog1Name') or not item.get('catalog1Id'):
            cat1_name = '未知'
            item['catalog1Id'] = '00000'
            item['catalog1Name'] = cat1_name
        if not item.get('catalog2Id') and cat2_name:
            item['catalog2Id'] = md5(cat2_name)

        return item
# =========================
